<template>
<div>
  <DataTable
    :value="servers"
    v-if="servers.length > 0"
  >
    <Column header="Name">
      <template #body="{ data }">
        {{ data.server }}:{{ data.port }}
      </template>
    </Column>
    <Column header="Configs">
      <template #body="{ data }">
        {{ data.basicConfigs ? data.basicConfigs.length : '' }}
      </template>
    </Column>
    <Column header="Locations">
      <template #body="{ data }">
        {{ data.locationConfigs ? data.locationConfigs.length : '' }}
      </template>
    </Column>
    <Column header="#">
      <template #body="{ index }">
        <Button
          severity="secondary"
          size="small"
          @click="editServer( index)"
          variant="text"
          label="Edit"
        ></Button>
        <Button
          severity="danger"
          size="small"
          @click="deleteServer($event, index)"
          variant="text"
          label="Delete"
        ></Button>
      </template>
    </Column>
  </DataTable>
  <div class="flex h-30px items-center justify-center gap-2" v-else>
    <Button icon="pi pi-check" size="small" style="width: 120px" @click="addServerFn"
    >+ Server</Button
    >
  </div>
  <add-server-dialog
    ref="addServerDialogRef"
  ></add-server-dialog>
</div>
</template>
<script setup lang="ts">
// Http 中显示 Server or Stream
import { ref, useTemplateRef } from 'vue'
import type { ServerConfig } from '@/types/dt/Dt.ts'
import { useConfirm } from 'primevue/useconfirm'
import AddServerDialog from '@/views/tools/nginx/detail-comps/add-http-server-dialog.vue'

const confirm = useConfirm()
const servers = ref<ServerConfig[]>([])
// Server 配置

const addServerDialog = useTemplateRef('addServerDialogRef')
function addServerFn() {
  addServerDialog.value!.open()
    .then(v => {
      servers.value.push(v)
    })
    .catch(e => {
      console.log(e)
    })
}
function editServer(index: number) {
  const server = servers.value[index]
  addServerDialog.value!.open(server)
  .then(v => {
    servers.value[index] = v
  }).catch(e => {
    console.error(e)
  })
}
function deleteServer(event: MouseEvent, index: number) {
  confirm.require({
    target: event.currentTarget! as HTMLElement,
    message: 'Do you want to delete this record?',
    icon: 'pi pi-exclamation-triangle',
    rejectProps: {
      label: 'Cancel',
      severity: 'secondary',
      outlined: true,
    },
    acceptProps: {
      severity: 'danger',
      label: 'Delete',
    },
    accept: () => {
      servers.value.splice(index, 1)
    },
  })
}
function getConfig (): ServerConfig[]{
  return servers.value
}
function setConfig (config: ServerConfig[]) {
  servers.value = config
}
defineExpose({
  addServer: addServerFn, getConfig, setConfig
})
</script>

<style scoped></style>
